// Register page module
// ====================

define(['zepto', 'wx', 'sui'], function($, wx) {
  return {
    init: function(data) {
      // config WeChat JS SDK
      this.data = data
      this.isDebug = location.search.indexOf('debug=true') > 0;
      this.initWx(data.jsConfig, false)
      this.onClickScanIcon()
    },
    
    initWx: function(config, shareable) {
      var isDebug = location.search.indexOf('debug=true') > 0
      var apis = (shareable == false ? ['hideMenuItems', 'getLocation', 'scanQRCode'] : ['onMenuShareTimeline', 'onMenuShareAppMessage', 'getLocation', 'scanQRCode'])
      var that = this;
      
      wx.config({
        debug: isDebug,
        appId: config.appid,
        timestamp: config.timestamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: apis
      })
      
      wx.ready(function() {
        
        wx.getLocation({
          type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            that.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            that.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            that.speed = res.speed; // 速度，以米/每秒计
            that.accuracy = res.accuracy; // 位置精度
          },
          cancel: function (res) {
            $.toast("请允许获取地理位置");
          }
        });
        
        if(shareable == false) {
          wx.hideOptionMenu()
        } else {
          wx.onMenuShareTimeline(that.getShareMessage(shareData))
          wx.onMenuShareAppMessage(that.getShareMessage(shareData))
        }
        
      })
    },
    
    /**
     * Click handler for QR scan icon
     */
    onClickScanIcon: function() {
      var that = this;
      
      $('.qrscan-icon').on('click', function(e) {
        e.preventDefault()
        wx.ready(function() {
          wx.scanQRCode({
            needResult: 1,
            scanType: ['qrCode'],
            success: function(res) {
              that.scanQrCode(res)
            }
          })
        })
      })
    },

    /**
     * Callback to process QR scan result
     */
    scanQrCode: function(res) {
      var that = this;
      if(res != null && res != undefined) {
        
        var courseScheduleId = res.resultStr.split("|")[0];
        var timestamp = res.resultStr.split("|")[1];
        
        that.validateQrcode(courseScheduleId, timestamp);
        
      }else {
        
        console.log("can not redirect to signin course page with res:" + res.resultStr)
        window.location.href = __CTX__.root + "/signin-error?message=签到扫码异常"
      }
    },
    
    validateQrcode: function(courseScheduleId, timestamp) {
      var that = this;
      
      $.ajax({
        type: "POST",
        url:  window.__CTX__.root + "/signin/valid",
        data: {
          "longitude": that.longitude,
          "latitude": that.latitude,
          "course": courseScheduleId,
          "timestamp": timestamp,
          "ignoretime": that.isDebug ? true : false
        }
      }).done(function(data) {
        data = JSON.parse(data)
        if(parseInt(data.code) == 0) {  
          that.formSubmit(window.__CTX__.root + '/scan-result', {'course': courseScheduleId }, 'POST').submit();
        } else {
          $.toast(data.message);
        }
      }).fail(function() {
        $.toast("扫描二维码失败");
      })
    },
    
    formSubmit: function (url, data, method) {
        if (method == null) method = 'POST';
        if (data == null) data = {};

        var form = $('<form>').attr({
            method: method,
            action: url
        }).css({
            display: 'none'
        });

        var addData = function (name, data) {
            if ($.isArray(data)) {
                for (var i = 0; i < data.length; i++) {
                    var value = data[i];
                    addData(name + '[]', value);
                }
            } else if (typeof data === 'object') {
                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        addData(name + '[' + key + ']', data[key]);
                    }
                }
            } else if (data != null) {
                form.append($('<input>').attr({
                    type: 'hidden',
                    name: String(name),
                    value: String(data)
                }));
            }
        };

        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                addData(key, data[key]);
            }
        }

        return form.appendTo('body');
    }
    
  }
})